import React, {useState} from "react";
import {Button, Chip, Divider, Grid, Paper, Typography} from "@material-ui/core";
import MenuDropDown from "../../../../Common/MenuDropDown/MenuDropDown";
import {useDispatch} from "react-redux";
import {selectDeselectResult} from "../../../../../../../redux/reducers/editor";
import {resultOperator} from "../filterData";


export default function ResultDetails(props) {
  // Props
  const {classes, resultData, selectedResult, styles} = props;

  // Local constants
  const dispatch = useDispatch();
  const [selection, setSelection] = useState({
    result: {id: "", type: "", name: "", values: []},
    operator: {id: "", name: ""},
    values: {id: "", type: "", name: ""},
    chips: selectedResult ? selectedResult : []
  });

  const handleChooseResult = (label, value) => {
    if (label === "result") {
      setSelection({
        ...selection,
        [label]: value,
        operator: {id: "", name: ""},
        values: {id: "", type: "", name: ""}
      });
    } else {
      setSelection({
        ...selection,
        [label]: value
      });
    }
  };
  const handleAddResult = () => {
    let newResultData = resultData;
    newResultData.forEach(result => {
      if (result.id === selection.result.id) {
        result.values = result.values.filter(a => a.id !== selection.values.id)
      }
    })
    const newChips = selection.chips;
    newChips.push({
      id: selection.result.id,
      name: selection.result.name,
      operatorId: selection.operator.id,
      operatorName: selection.operator.name,
      values: selection.values
    })
    setSelection({
      ...selection,
      operator: {id: "", name: ""},
      values: {id: "", type: "", name: ""}
    });
    dispatch(selectDeselectResult(newChips, newResultData));
  };

  const handleDeleteResult = (chip) => {
    let newResultData = resultData;
    newResultData.forEach(result => {
      if (result.id === chip.id) {
        result.values.push({id: chip.values.id, type: chip.values.type, name: chip.values.name});
        result.values = result.values.sort((a, b) => (a.name > b.name) ? 1 : -1);
      }
    })
    const newChips = selection.chips.filter(a => a.values.id !== chip.values.id);
    setSelection({
      ...selection,
      operator: {id: "", name: ""},
      values: {id: "", type: "", name: ""},
      chips: newChips
    })
    dispatch(selectDeselectResult(newChips, newResultData));
  }

  const handleClearAllResults = () => {
    let newResultData = resultData;
    let newChips = []
    selection.chips.forEach(chip => {
      newResultData.forEach(result => {
        if (result.id === chip.id) {
          result.values.push({id: chip.values.id, type: chip.values.type, name: chip.values.name});
          result.values = result.values.sort((a, b) => (a.name > b.name) ? 1 : -1);
        }
      })
    })
    setSelection({
      ...selection,
      operator: {id: "", name: ""},
      values: {id: "", type: "", name: ""},
      chips: newChips
    })
    dispatch(selectDeselectResult(newChips, newResultData));
  }

  return (
    <>
      <Grid container direction="column">
        <Grid item className={classes.gutterTopBottom}>
          <Paper elevation={10}>
            <Grid container direction="row">
              <Grid item xs>
                <MenuDropDown
                  displayLabel={"Outcomes of activities"}
                  parameterName={"result"}
                  source={resultData}
                  value={selection.result.name}
                  handleSelection={handleChooseResult}
                />
              </Grid>

              {selection.result.name === "Scaled" ||
              selection.result.name === "Max" ||
              selection.result.name === "Raw" ||
              selection.result.name === "Min" ? (
                <>
                  <Grid item xs>
                    <MenuDropDown
                      middle={true}
                      displayLabel={"Operator"}
                      parameterName={"operator"}
                      source={resultOperator}
                      value={selection.operator.name}
                      handleSelection={handleChooseResult}
                    />
                  </Grid>
                  <Grid item xs>
                    <MenuDropDown
                      middle={true}
                      displayLabel={"Values"}
                      parameterName={"values"}
                      source={selection.operator.name ? selection.result.values : []}
                      value={selection.values.name}
                      handleSelection={handleChooseResult}
                    />
                  </Grid>
                </>
              ) : selection.result.name === "Success" ||
              selection.result.name === "Completed" ||
              selection.result.name === "Response" ? (
                <Grid item xs>
                  <MenuDropDown
                    middle={true}
                    displayLabel={"Values"}
                    parameterName={"values"}
                    source={selection.result.values}
                    value={selection.values.name}
                    handleSelection={handleChooseResult}
                  />
                </Grid>
              ) : <></>}
              <Button
                onClick={handleAddResult}
                disabled={selection.values.name === ""}
                variant="contained"
                color="primary"
                className={styles.applyButton}
              >
                Select
              </Button>
            </Grid>
          </Paper>
        </Grid>
        <Grid container justify="space-between" alignItems="center" className={classes.gutterTopBottom}>
          <Grid item>
            <Typography variant="overline">Selected outcomes of activities</Typography>
          </Grid>
          <Grid item>
            <Button
              color="primary" variant="outlined" size="small"
              onClick={handleClearAllResults}
              disabled={selection.chips.length === 0}
            >
              <Typography variant="overline">Clear selections</Typography>
            </Button>
          </Grid>
        </Grid>
        <Grid item style={{minHeight: 40}}>
          {selection.chips.map((chip, index) => {
            return (
              <Chip
                key={index}
                label={chip.operatorName ?
                  chip.name + " | " + chip.operatorName + " | " + chip.values.name
                  : chip.name + " | " + chip.values.name}
                variant="default"
                onDelete={() => handleDeleteResult(chip)}
                color="primary"
                className={styles.chipMargin}
              />
            )
          })}
        </Grid>
        <Grid item className={classes.gutterBottom}>
          <Divider/>
        </Grid>
      </Grid>
    </>
  );
}
